package com.dries.portal.module.user.controller;

import com.dries.common.api.CommonResult;
import com.dries.portal.module.user.form.RegisterForm;
import com.dries.portal.module.user.form.UserLoginForm;
import com.dries.portal.module.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户
 *
 * @author zsy
 * @email samphsanie@gmail.com
 * @date 2020-06-28 17:11:18
 */
@RestController
@Api(tags = "会员登录注册管理", value = "UserController")
@RequestMapping("/portal/user")
@Slf4j
public class UserController {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Resource
    private UserService userService;

    @ApiOperation("会员注册")
    @PostMapping("/register")
    public CommonResult register(@Valid @RequestBody RegisterForm registerForm) {

        return userService.registerUser(registerForm);

    }

    @ApiOperation("会员登录")
    @PostMapping("/login")
    public CommonResult login(@Valid @RequestBody UserLoginForm loginForm) {

        return userService.login(loginForm);

    }

    @ApiOperation("获取会员信息")
    @GetMapping("/info")
    public CommonResult info(Principal principal) {

        if (principal == null) {
            log.info("获取会员信息失败");
            return CommonResult.unauthorized(null);
        }
       return userService.getCurrentUser();

    }

    @ApiOperation("获取指定用户信息")
    @GetMapping("/info/{userId}")
    public CommonResult userInfo(@PathVariable String userId) {

        return userService.getUserById(Long.valueOf(userId));

    }

    @ApiOperation(value = "刷新token")
    @GetMapping("/refreshToken")
    public CommonResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = userService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }
}
